const fs = require('fs');
const path = require('path');
const Promise1 = require('./source/promise-v3');

function readFile(url, encoding) {
    // 延迟对象的使用场景
    let dfd = Promise1.deferred();
    fs.readFile(url, encoding, function (err, data) {
        if (err) {
            return dfd.reject(err);
        }
        dfd.resolve(data)
    })
    return dfd.promise
}

readFile(path.resolve(__dirname, './a.txt'), 'utf-8').then(res => {
    console.log(res);
    return 1
}).then(res => {
    console.log(res);
})

// catch捕获异常

// Promise.resolve 创建一个成功
Promise.resolve('ok').then(res => {
    console.log(res)
})


// Promise.reject 创建一个失败
Promise.reject('error').then(res => {
    console.log(res)
}, (err) => {
    console.log(err)
})

//catch

P1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject('is error')
    }, 2000)
}).catch(err => {
    console.log('err is:', err)
})

Promise.all = function (promises) {
    let result = [];
    let times = 0;
    return new Promise((resolve, reject) => {
        function processResult(data, i) {
            result[i] = data; // 映射结果
            if (++times === promises.length) {
                resolve(result)
            }
        }
        for (let i = 0; i < promises.length; i++) {
            const promise = promises[i]
            Promise.resolve(promise).then(data => {
                processResult(data, i);
            }, reject)
        }
    })
}

// all
// 执行完毕后将结果的放到数组里面，all的含义是所有的都成功才会成功，有一个失败则失败
Promise.all([
    readFile(path.resolve(__dirname, './a.txt'), 'utf-8'),
    readFile(path.resolve(__dirname, './b.txt'), 'utf-8'),
    '1234',
    '4567'
]).then(res => {
    console.log(res)
})